package za.um.td.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import jmetest.terrain.TestProceduralSplatTexture;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLUtil {    
    /**
     * Returns the first XML child tag with the specified name.
     * 
     * @param node The node to search children of
     * @param name The name of the node to search for, case-sensitive.
     * @return The child with the specified name, or null if none exists.
     */
    public static Node getChildNode(Node node, String name) {
        Node child = node.getFirstChild();
        while (child != null && !child.getNodeName().equals(name) ){
            child = child.getNextSibling();
        }
        return child;
    }
    
    public static Node loadDocument(InputStream in, String rootElementName) throws IOException{
        try {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(in);

            NodeList list = doc.getElementsByTagName(rootElementName);
            
            //modified by Th0r
            //If index is greater than or equal to the number of nodes in the list, this returns null. 
            return list.item(0);            
        } catch (ParserConfigurationException ex) {
            throw new IOException("Error occured while reading XML document: "+ex.getLocalizedMessage());
        } catch (SAXException ex) {
            throw new IOException("Error occured while reading XML document: "+ex.getLocalizedMessage());
        }
    }
    
    /**
     * Returns an attribute of the specified tag with the name provided.
     * 
     * @param node
     * @param name
     * @return The attribute if its defined, or null.
     */
    public static String getAttribute(Node node, String name, String defVal){
        Node att = node.getAttributes().getNamedItem(name);
        return att == null ? defVal : att.getNodeValue();
    }
    
    public static String getAttribute(Node node, String name){
        return getAttribute(node,name,null);
    }
    
    public static boolean getBoolAttribute(Node node, String name){
        return Boolean.parseBoolean(getAttribute(node,name));
    }
    
    public static boolean getBoolAttribute(Node node, String name, boolean defVal){
        String att = getAttribute(node, name);
        if (att == null) return defVal;
        return Boolean.parseBoolean(att);
    }
    
    public static float getFloatAttribute(Node node, String name){
        return Float.parseFloat(getAttribute(node,name,"0"));
    }
    
    public static float getFloatAttribute(Node node, String name, float defVal){
        String att = getAttribute(node, name);
        if (att == null) return defVal;
        return Float.parseFloat(att);
    }
    
    public static int getIntAttribute(Node node, String name, int defVal){
        String att = getAttribute(node, name);
        if (att == null) return defVal;
        return Integer.parseInt(att);
    }
    
    public static int getIntAttribute(Node node, String name){
    	String attr = getAttribute(node,name);
    	if(attr != null)
    		return Integer.parseInt(getAttribute(node,name));
    	return 0;
    }
    
    public static float str2float(String str){
        return Float.parseFloat(str.trim());
    }
    
    /*
    public static Vector3f getVec3Attribute(Node node, String name){
        return getVec3Attribute(node, name, null);
    }
    
    public static Vector3f getVec3Attribute(Node node, String name, Vector3f defVal){
        String att = getAttribute(node, name);
        if (att == null)
            return defVal;
        
        String split[] = att.split(",");
        return new Vector3f(str2float(split[0]),
                            str2float(split[1]),
                            str2float(split[2]));
    }
    
    public static Quaternion getQuatAttribute(Node node, String name){
        return getQuatAttribute(node, name, null);
    }
    
    public static Quaternion getQuatAttribute(Node node, String name, Quaternion defVal){
        String att = getAttribute(node, name);
        if (att == null)
            return defVal;
        
        String split[] = att.split(",");
        return new Quaternion(str2float(split[0]),
                              str2float(split[1]),
                              str2float(split[2]),
                              str2float(split[3]));
    }
    
    public static ColorRGBA getRGBAAttribute(Node node, String name){
        return getRGBAAttribute(node, name, null);
    }
    
    public static ColorRGBA getRGBAAttribute(Node node, String name, ColorRGBA defVal){
        String att = getAttribute(node, name);
        if (att == null)
            return defVal;
        
        if (att.startsWith("#")){
            // parse HEX color
            att = att.substring(1);
            
            int rgb = Integer.parseInt(att, 16);
            if (att.length() == 6)
                rgb = (rgb << 8) | 0xFF;

            ColorRGBA color = new ColorRGBA();
            color.fromIntRGBA(rgb);
            return color;
        }else{
            String split[] = att.split(",");
            if (split.length == 3){
                return new ColorRGBA(str2float(split[0]),
                                     str2float(split[1]),
                                     str2float(split[2]),
                                     1.0f);
            }else{
                return new ColorRGBA(str2float(split[0]),
                                     str2float(split[1]),
                                     str2float(split[2]),
                                     str2float(split[3]));
            }
        }
    }*/
    /*
    public static void main(String[] args) 
    {
    	URL xmlUrl=XMLUtil.class.getClassLoader().getResource("test/tile_0_0.xml");

    	try 
    	{
			Node tileNode = XMLUtil.loadDocument(xmlUrl.openStream(), "tile");
			
			System.out.println(tileNode.getNodeName());
			
			Node terrainNode = XMLUtil.getChildNode(tileNode, "terrain");
			
			String size = XMLUtil.getAttribute(terrainNode, "size");
			
			System.out.println("size="+size);
			
			String heightMap = terrainNode.getTextContent();
			
			System.out.println("heightMap="+heightMap);
			
			
		} 
    	catch (IOException e) {
			e.printStackTrace();
		}
    }*/
}
